#!/usr/bin/env bash

set -euo pipefail

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "macos_fifo_smoke.sh is intended for macOS hosts" >&2
  exit 0
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

CLI_BIN="${REPO_ROOT}/build/asycipcctl"
SERVER_BIN="${REPO_ROOT}/build/asycipc_demo_server"
CLIENT_BIN="${REPO_ROOT}/build/asycipc_demo_client"

for bin in "$CLI_BIN" "$SERVER_BIN" "$CLIENT_BIN"; do
  if [[ ! -x "$bin" ]]; then
    echo "required binary not found or not executable: $bin" >&2
    echo "build them first: cmake --build build --target asycipc_demo_server asycipc_demo_client asycipcctl" >&2
    exit 1
  fi
done

runtime_root="${ASYIPC_RUNTIME_DIR:-}"
created_runtime_dir=0
if [[ -z "$runtime_root" ]]; then
  base_tmp="${TMPDIR:-/tmp}"
  runtime_root="$(mktemp -d "${base_tmp%/}/asycipc_fifo_XXXXXX")"
  created_runtime_dir=1
fi

mkdir -p "$runtime_root"

cleanup() {
  local code=${1:-0}
  trap - EXIT INT TERM
  if [[ -n "${server_pid:-}" ]]; then
    kill "$server_pid" 2>/dev/null || true
    wait "$server_pid" 2>/dev/null || true
  fi
  if [[ -n "${client_pid:-}" ]]; then
    kill "$client_pid" 2>/dev/null || true
    wait "$client_pid" 2>/dev/null || true
  fi
  if [[ $created_runtime_dir -eq 1 ]]; then
    rm -rf "$runtime_root"
  fi
  exit "$code"
}
trap 'cleanup "$?"' EXIT
trap 'cleanup 130' INT
trap 'cleanup 143' TERM

export ASYIPC_RUNTIME_DIR="$runtime_root"

echo "[+] starting demo server (FIFO transport)" >&2
"$SERVER_BIN" >"$runtime_root/server.log" 2>&1 &
server_pid=$!

sleep 1

echo "[+] starting demo client" >&2
"$CLIENT_BIN" >"$runtime_root/client.log" 2>&1 &
client_pid=$!

wait "$client_pid"
wait "$server_pid"

echo "[+] verifying CLI session status" >&2
"$CLI_BIN" sessions list "$runtime_root" --format json >/dev/null

echo "[+] macOS FIFO smoke test completed" >&2
